package com.sxh.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.google.common.hash.Hashing;
import com.sxh.user.Utils.*;
import com.sxh.user.exception.BaseException;
import com.sxh.user.exception.PermissionException;
import com.sxh.user.feign.UserFeignClient;
import com.sxh.user.map.UserMap;
import com.sxh.user.model.PageUser;
import com.sxh.user.model.UserInfo;
import com.sxh.user.model.Users;
import com.sxh.user.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String DEFAULT_PASSWORD="123456";
    private static final String SUPER_ADMIN="super_admin";
    private static final String ADMIN="admin";
    private static final String USER="user";


    @Autowired
    private UserMap userMap;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RocketMQProducerUtil rocketMQProducerUtil;
    @Autowired
    private UserService proxy;
//    @Autowired
//    private IPUtil ipUtil;
    //用户注册
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void userRegister(Users user) {
        if(StringUtils.isEmpty(user.getPassword())){
            //没有密码,赋值默认密码
            user.setPassword(DEFAULT_PASSWORD);
        }
        //生成id
        Long id = Math.abs(Hashing.murmur3_128()    //参考AI
                .hashString(user.getUsername(), StandardCharsets.UTF_8)
                .asLong());
        user.setUserId(id);
        //查询用户是否存在
        Users userQuery = userMap.queryById(id);
        if(userQuery!=null){
            throw new BaseException("用户已存在");
        }
        //添加创建时间
        user.setGmtCreate(LocalDateTime.now());
        //插入用户表
        int userInsert = userMap.insertUser(user);
//        int a=1/0;
        //赋予默认角色
        userFeignClient.bindDefaultRole(id);
        proxy.sendMessage(user, id, id,"INSERT","用户注册");
    }
    //用户登录
    @Override
    public String userLogin(String username, String password) {
        //根据用户名生成id
        Long id = Math.abs(Hashing.murmur3_128()    //算法参考AI
                .hashString(username, StandardCharsets.UTF_8)
                .asLong());
        //查询用户是否存在
        Users users = userMap.queryById(id);
        if(users==null){
            throw new BaseException("请先注册");
        }
        if(!password.equals(users.getPassword())){
            throw new BaseException("账号或密码错误");
        }
        //发送日志
        proxy.sendMessage(users, id, id,"SELECT","用户登录");
        //生成token
        return jwtUtil.createToken(id);
    }
    //修改用户信息
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updateUser(UserInfo userInfo, Long ownerId) {
        if(userInfo.getUserId()==null){
            Long id = Math.abs(Hashing.murmur3_128()    //参考AI
                    .hashString(userInfo.getUsername(), StandardCharsets.UTF_8)
                    .asLong());
            userInfo.setUserId(id);
        }
        //查询要修改的用户角色码
        String userRoleCode = userFeignClient.getUserRoleCode(userInfo.getUserId());
        Users user = new Users(userInfo.getUserId(),userInfo.getUsername(),userInfo.getPassword(),userInfo.getEmail(),userInfo.getPhone(),null);
        //查询当前用户角色码
        String ownerRoleCode = userFeignClient.getUserRoleCode(ownerId);
        //判断操作者权限
        if(USER.equals(ownerRoleCode)&&
                ownerId.equals(userInfo.getUserId())){
            //普通用户修改自己的信息
            userMap.updateUser(user);
            //发送日志
            proxy.sendMessage(user, userInfo.getUserId(), ownerId,"UPDATE","修改用户信息");
        } else if (ADMIN.equals(ownerRoleCode)
                && USER.equals(userRoleCode)) {
            //管理员修改普通用户信息
            userMap.updateUser(user);
            //发送日志
            proxy.sendMessage(user, userInfo.getUserId(), ownerId,"UPDATE","修改用户信息");
        } else if (SUPER_ADMIN.equals(ownerRoleCode)) {
            //超级管理员修改所有用户信息
            userMap.updateUser(user);
            if(USER.equals(userInfo.getRoleCode())&&ADMIN.equals(userRoleCode)){
                //降级权限
                userFeignClient.downgradeToUser(userInfo.getUserId());
            } else if (ADMIN.equals(userInfo.getRoleCode())&&USER.equals(userRoleCode)) {
                //升级权限
                userFeignClient.upgradeToAdmin(userInfo.getUserId());
            }
            //发送日志
            proxy.sendMessage(user, userInfo.getUserId(), ownerId,"UPDATE","修改用户信息");
        }else {
            throw new PermissionException("权限不足");
        }
    }
    //密码重置
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void resetPassword(Long id,Long ownerId) {
        //查询要重置的用户角色码
        String userRoleCode = userFeignClient.getUserRoleCode(id);
        if(StringUtils.isEmpty(userRoleCode)){
            throw new BaseException("用户不存在");
        }
        //查询当前用户角色码
        String ownerRoleCode = userFeignClient.getUserRoleCode(ownerId);
        Users user = new Users(id,null,DEFAULT_PASSWORD,null,null,null);
        if(SUPER_ADMIN.equals(ownerRoleCode)){
            //超级管理员重置用户密码
            userMap.updateUser(user);
            //发送日志
            proxy.sendMessage(user,id,ownerId,"UPDATE","重置密码");
        } else if (ADMIN.equals(ownerRoleCode) && USER.equals(userRoleCode)) {
            //管理员重置用户密码
            userMap.updateUser(user);
            //发送日志
            proxy.sendMessage(user,id,ownerId,"UPDATE","重置密码");
        } else if (USER.equals(userRoleCode)&&id.equals(ownerId)) {
            //用户重置自己的密码
            userMap.updateUser(user);
            //发送日志
            proxy.sendMessage(user,id,ownerId,"UPDATE","重置密码");
        }else {
            throw new PermissionException("权限不足");
        }
    }
    //查询用户信息
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public UserInfo queryUser(Long id,Long ownerId) {
        //查询用户
        Users user = userMap.queryById(id);
        if(user == null){
            BaseException.cast("用户不存在");
            return null;
        }
        //查询当前用户角色码
        String ownerRoleCode = userFeignClient.getUserRoleCode(ownerId);
        //查询用户权限
        String userRoleCode = userFeignClient.getUserRoleCode(id);
        //判断是否有查询权限
        if(SUPER_ADMIN.equals(ownerRoleCode)
                ||(ADMIN.equals(ownerRoleCode)&&USER.equals(userRoleCode))
                ||(USER.equals(ownerRoleCode)&&id.equals(ownerId))){
//            //查询用户
//            Users user = userMap.queryById(id);
            //发送日志
            proxy.sendMessage(user,id,ownerId,"SELECT","查询用户信息");
//            if(user==null){
//                //用户不存在返回null
//                System.err.println("用户不存在");
//                return null;
//            }
            return new UserInfo(user.getUserId(), user.getUsername(),
                    user.getPassword(), user.getEmail(),
                    user.getPhone(), user.getGmtCreate(),
                    userRoleCode);
        }else {
            throw new PermissionException("权限不足");
        }
    }
    //分页用户列表
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public PageUser queryUserList(Integer pageNum, Integer pageSize,Long ownerId) {
        PageUser pageUser = new PageUser();
        List<UserInfo> userInfoList = new ArrayList<>();
        Integer begin = (pageNum - 1) * pageSize;
        //查询当前用户角色码
        String ownerRoleCode = userFeignClient.getUserRoleCode(ownerId);
        if(ADMIN.equals(ownerRoleCode)){
            //管理员获得用户列表
            //先根据权限查询普通用户user_id
            List<Long> userIdList = userFeignClient.queryUserIdByRoleId(USER);
            //再根据idList分页查询
            List<Users> usersList = userMap.queryByIdList(userIdList, begin, pageSize);
            //给user加上权限，封装给userInfo
            for (Users user : usersList) {
                UserInfo userInfoTemp = new UserInfo();
                BeanUtils.copyProperties(user, userInfoTemp);
                userInfoTemp.setRoleCode(USER);
                userInfoList.add(userInfoTemp);
            }
            //封装返回值
            pageUser.setPageSize(pageSize);
            pageUser.setPageNumber(pageNum);
            pageUser.setTotalElements(usersList.size());
            pageUser.setContent(userInfoList);

            //发送日志
            proxy.sendMessage(new Users(), null, ownerId, "SELECT", "分页查询用户");
            return pageUser;
        } else if (SUPER_ADMIN.equals(ownerRoleCode)) {
            //超级管理员查所有用户
            //先根据权限查询普通用户user_id和管理员id
            List<Long> userIdList = userFeignClient.queryUserIdByRoleId(USER);
            List<Long> userIdListAdmin = userFeignClient.queryUserIdByRoleId(ADMIN);
            //再根据idList分页查询
            //查询普通用户
            List<Users> usersList = userMap.queryByIdList(userIdList, begin, pageSize);
            for (Users user : usersList) {
                UserInfo userInfoTemp = new UserInfo();
                BeanUtils.copyProperties(user, userInfoTemp);
                userInfoTemp.setRoleCode(USER);
                userInfoList.add(userInfoTemp);
            }
            //查询管理员
            List<Users> usersListAdmin = userMap.queryByIdList(userIdListAdmin, begin, pageSize); //
            for (Users user : usersListAdmin) {
                UserInfo userInfoTemp = new UserInfo();
                BeanUtils.copyProperties(user, userInfoTemp);
                userInfoTemp.setRoleCode(ADMIN);
                userInfoList.add(userInfoTemp);
            }
            //封装返回值
            pageUser.setPageSize(pageSize);
            pageUser.setPageNumber(pageNum);
            pageUser.setTotalElements(userInfoList.size());
            pageUser.setContent(userInfoList);
            //发送日志
            proxy.sendMessage(new Users(), null, ownerId, "SELECT", "分页查询用户");
            return pageUser;
        }else {
            System.err.println("权限不足");
            throw new PermissionException("权限不足");
        }
    }
    //发送日志
    public void sendMessage(Users user, Long id,Long ownerId,String type,String logId) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        userInfo.setRoleCode("user");

        //获取ip
        String ip = IPUtil.getClientIp();

        Map<String, Object> wrapper = new HashMap<>();
        wrapper.put("userId", id);
        wrapper.put("action", type);
        wrapper.put("ip", ip);
        wrapper.put("detail", userInfo);
        wrapper.put("optionId", ownerId);
        wrapper.put("optionTime",LocalDateTime.now());
        String jsonString = JSON.toJSONString(wrapper);
        rocketMQProducerUtil.sendMessageAsync(type, jsonString, new LogSendCallback(logId));
    }

}
